package com.clock.album;

import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import ohos.aafwk.ability.AbilityPackage;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.PageSliderProvider;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class PagerProvider extends PageSliderProvider {
    private ArrayList<Integer> mList=new ArrayList<>();
    private Context mContext;
    private DataAbilityHelper helper;

    public PagerProvider(Context mContext,ArrayList<Integer> mList) {
        this.mContext=mContext;
        this.mList=mList;
        helper = DataAbilityHelper.creator(mContext);
        notifyDataChanged();
    }
    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object createPageInContainer(ComponentContainer componentContainer, int i) {
        SubsamplingScaleImageView image =new SubsamplingScaleImageView (mContext);
        image.setPixelMap(getPixelMapById(mList.get(i)+""));
        componentContainer.addComponent(image);
        return image;
    }

    @Override
    public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
        componentContainer.removeComponent((Component) o);
    }

    @Override
    public boolean isPageMatchToObject(Component component, Object o) {
        return false;
    }
    private PixelMap getPixelMapById(String id){
        PixelMap pixelMap = null;
        ImageSource imageSource = null;
        Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, id);
        FileDescriptor fd = null;
        try {
            fd = helper.openFile(uri, "r");
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            imageSource = ImageSource.create(fd, null);
            pixelMap = imageSource.createPixelmap(null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (imageSource != null) {
                imageSource.release();
            }
        }
        return pixelMap;
    }
}
